package common

import (
	"blog/config"
	"blog/models"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"sync"
)

var Template models.HtmlTemplate

func LoadTemplate() {
	w := sync.WaitGroup{}
	w.Add(1)
	go func() {
		var err error
		Template, err = models.InitTemplate(config.Cfg.System.CurrentDir + "/template/")
		fmt.Println(config.Cfg.System.CurrentDir)
		if err != nil {
			panic(err)
		}
		w.Done()
	}()
	w.Wait()
}

func GetRequestJsonParam(r *http.Request) (params map[string]interface{}) {
	body, _ := ioutil.ReadAll(r.Body)
	_ = json.Unmarshal(body, &params)
	return
}

func Success(w http.ResponseWriter, data interface{}) {
	//接收用户名和密码，返回对于json数据
	w.Header().Set("Content-Type", "application/json")
	result := models.Result{
		Error: "",
		Data:  data,
		Code:  200,
	}
	jsonStr, _ := json.Marshal(result)
	_, err := w.Write(jsonStr)
	if err != nil {
		log.Println(err)
	}
}
func Error(w http.ResponseWriter, err error) {
	//接收用户名和密码，返回对于json数据
	w.Header().Set("Content-Type", "application/json")
	result := models.Result{
		Error: err.Error(),
		Code:  -999,
	}
	jsonStr, _ := json.Marshal(result)
	_, err = w.Write(jsonStr)
	if err != nil {
		log.Println(err)
	}
}
